package me.hl.concurrent;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingDeque;

/**
 * Created by Planck on 2016/1/29.
 */
public class BlockingQueueTest implements Runnable {

    public static BlockingQueue<String> queue = new LinkedBlockingDeque<>(3);

    private int index;

    public BlockingQueueTest(int index) {
        this.index = index;
    }


    public void run() {
        //add如果没空间将会丢失
        //put如果没有空间将会等待
        try {
            queue.put(String.valueOf(index));
            System.out.println("第" + String.valueOf(index) + "个被放进队列");
        } catch (Exception e) {

        }
    }

    public static void main(String args[]) {
        ExecutorService executorService = Executors.newCachedThreadPool();
        for (int i = 0; i < 20; i++) {
            executorService.execute(new BlockingQueueTest(i));
        }
        for (int i = 0; i < 20; i++) {
            try {
                Thread.sleep(1000);
            } catch (Exception e) {

            }
            executorService.execute(() -> {
                try {
                    String str = queue.take();
                    System.out.println("第" + str + "个已经被取出");
                } catch (Exception e) {
                }
            });
        }
        executorService.shutdown();
    }
}
